package cc.ttiot.service.dataCollection.serial.protocol.modbusRtu;

/**
 * @Description: 串口上应用ModbusRtu协议的modbus主机类
 * @Author :
 * @Version :
 * @Date :
 */

import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.msg.*;
import java.util.Arrays;

public class ModbusRtuMaster {

    private final ModbusMaster master;

    public ModbusRtuMaster(ModbusMaster master) {
        this.master = master;
    }

    public void close() {
        master.destroy();
    }

    /**
     * 读开关量型的输入信号
     *
     * @param slaveId 从站地址
     * @param start   起始偏移量
     * @param len     待读的开关量的个数
     */
    public void readDiscreteInputTest(int slaveId, int start, int len) {
        try {
            ReadDiscreteInputsRequest request = new ReadDiscreteInputsRequest(slaveId, start, len);
            ReadDiscreteInputsResponse response = (ReadDiscreteInputsResponse) master.send(request);
            if (response.isException()) {
                System.out.println("异常消息:" + response.getExceptionMessage());
            } else {
                System.out.println(Arrays.toString(response.getBooleanData()));
            }
        } catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读保持寄存器上的内容
     *
     * @param slaveId 从站地址
     * @param start   起始地址的偏移量
     * @param len     待读寄存器的个数
     */
    public short[] readHoldingRegistersTest(int slaveId, int start, int len) {
        short[] list = null;
        try {
            ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(slaveId, start, len);
            ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master.send(request);
            if (response.isException()) {
                System.out.println("异常消息:" + response.getExceptionMessage());
            } else {
                list = response.getShortData();
            }
        } catch (ModbusTransportException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 批量写数据到保持寄存器
     *
     * @param slaveId 从站地址
     * @param start   起始地址的偏移量
     * @param values  待写数据
     */
    public void writeRegistersTest(int slaveId, int start, short[] values) {
        try {
            WriteRegistersRequest request = new WriteRegistersRequest(slaveId, start, values);
            WriteRegistersResponse response = (WriteRegistersResponse) master.send(request);
            if (response.isException()) {
                System.out.println("异常消息:" + response.getExceptionMessage());
            } else {
                System.out.println("写入成功");
            }
        } catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

}
